CreateModelWindowsCount = 0;

function NewCreateModelWindow(ServiceParams,ModelName)
{
	
	var DialogResult = $.Deferred();
	
	AjaxCallStatus = GetObjects("svc/search/getemptymodel?model="+ModelName);
	AjaxCallStatus.then(function()
	{
		var XMLresp = GetLastAJAXResponse();
		var WinDivID = CreateDomForWindow();
		DialogResult = CreateModelWindow(XMLresp,WinDivID,ServiceParams);
		TurnDivIntoDialog(WinDivID);
		return DialogResult;
	});
	AjaxCallStatus.fail(function()
	{
		CreateErrorWindow("Error!."
				+ " Check connection with server. " +
				"Cause: " + GetLastAJAXResponse());
		DialogResult.reject("fail");
		//return DialogResult;
	});
	
	
}

function CreateDomForWindow()
{
	var WindowsID = "CreateModelWindow-"+CreateModelWindowsCount;
	$('body').append("<div id='"+WindowsID+"' title='Create Model Window'></div>") //un nuevo div para una nueva ventana

	CreateModelWindowsCount++;

	return WindowsID;
}

function TurnDivIntoDialog(WinDivID)
{
	//Turn the dynamically generated dom into a dialog.
	$("#"+WinDivID).dialog(
			{
				modal: true,
				height:'auto',
				width:'auto',
				buttons: 
				{
					Close: function() 
					{
						$( this ).dialog( "close" );
						$(this).remove();
					},

				},
				close: function(event, ui)
				{
					$(this).dialog( "close" ); //Close the Dialog
					$(this).remove();	//Remove all the appended Dom and its assocciated events
				}
			});	

}

function CreateModelWindow(XMLresp, WinDivID, ServiceParams)
{
	
	var DialogRes = $.Deferred();
	
	var XMLresponse = XMLresp;
	//Hay que llevar los ID's del DOM creado Dinamicamente	
	var WindowsID = WinDivID;
	var SvcPath = "svc/crud";
	var SvcParams = ServiceParams;
	var FieldSetID = WindowsID+"-FieldSet";
	var CreateButtonID = WindowsID+"-CreateButton";

	var ModelData;
	
	//Armamos la grilla que manipula el DOM del XML
	$("#"+WindowsID).append("<form><fieldset id='"+FieldSetID+"'></fieldset></form>");//Empezamos a crear la tabla

	//We have just one object to see the schema, so we get the first
	$(XMLresponse).find('object').each(function()
	{

		var attrCount = 0;
		
		ModelData = $(this);
		/***********************************************************/
		//Load all the primitives of the current object in the list,
		//and all its logic

		ModelData.find('atribute').each 
		(function()
				{
					//ID unica para cada input, para agregarle un handler especifico onTextChange
		
					var CurrentAttribute = $(this);
		
					var InputID = FieldSetID +"-Input"+attrCount;
					
				
						$("#"+FieldSetID).append("<label for='"+InputID+"'>"+CurrentAttribute.attr("name")+": </label>");
						$("#"+FieldSetID).append("<input id='"+InputID+"' value='"+CurrentAttribute.text()+"' class='text ui-widget-content ui-corner-all'></input></br>");
						
						if (CurrentAttribute.attr("name") == "id")
						{
							$("#"+InputID).attr("readonly", true);
							$("#"+InputID).attr("title","The ID of a record can't be edited.");
						}

						
						
						//Adding validations regarding the type of data.
						if (CurrentAttribute.attr("type")=="int" || CurrentAttribute.attr("type")=="long")
						{
							$("#"+InputID).bind
							(
									'keyup',
									function(EventArgs)
									{
										this.value = this.value.replace(/[^0-9]/gi,'');
									}
							);
			
						}
						else if (CurrentAttribute.attr("type")=="double" || CurrentAttribute.attr("type")=="float" )
						{
							$("#"+InputID).bind
							(
									'keyup',
									function(EventArgs)
									{
										this.value = this.value.replace(/[^0-9\.]/gi,'');
									}
							);
			
						}
						else if ($(this).attr("type")=="date")
						{
							$('#'+InputID).datepicker(
									{
										changeMonth: true,
										changeYear: true,
										dateFormat: 'dd/mm/yy'
									});
						}
						else if ($(this).attr("type")=="boolean")
						{
							$('#'+InputID).attr('type','checkbox');
						} 
			
			
			
						//The handler for each input, tom modify the specific tah it should handle
						var CurrentCount = attrCount;
						$("#"+InputID).bind
						(
								'change',
								function(EventArgs)
								{
									var FunctionAttribute = CurrentAttribute
									FunctionAttribute.text($(this).val());
								}
						);	
		
					
					attrCount++;
				});	


			});

	$("#"+WindowsID).append("<button id='"+CreateButtonID+"' title='Create...'></button>");

	$( "#"+CreateButtonID ).button({text: false, icons: {primary: "ui-icon-check" }, title: "Commit Changes..."}
	).click(function()
			{
			    var SerializedObject = ModelData.prop('outerHTML');
				var AjaxRequestResult = CreateObject(SerializedObject, SvcPath+"?"+SvcParams);
				//If Ajax Success
				AjaxRequestResult.then(function(Result)
				{
					DialogRes.resolve("success");
					$("#"+WinDivID ).dialog( "close" );
					$("#"+WinDivID).remove();
				});
			});			


	return DialogRes;
}


